﻿using Sirenix.OdinInspector.Editor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TMPro;
using UnityEditor;
using UnityEngine;

namespace Miao.UI
{
    [CustomEditor(typeof(Option))]
    public class OptionEdtior : OdinEditor
    {
        private Option component;
        private int maxButtonSize = 10;
        private GameObject childPanelPrefab
        {
            get
            {
                return component.childPanelPrefab;
            }
        }

        override protected void OnEnable()
        {
            base.OnEnable();
            component = (Option)target;
        }
        public override void OnInspectorGUI()
        {
            int field = component.usePanelCount < maxButtonSize ? component.usePanelCount : maxButtonSize;
            component.usePanelCount = EditorGUILayout.IntField("创建按钮数量", field);
            //usePanelCount
            if (component.group != null)
            {
                int maxCashe = 0;
                while (component.group.childCount != component.usePanelCount && maxCashe != maxButtonSize)
                {
                    if (component.group.childCount > component.usePanelCount)
                    {
                        var child = component.group.GetChild(component.group.childCount - 1);
                        //child.parent = null;
                        GameObject.DestroyImmediate(child.gameObject, true);
                    }
                    else
                    {
                        GameObject newChild = (GameObject)PrefabUtility.InstantiatePrefab(childPanelPrefab);
                        newChild.transform.SetParent(component.group, false);
                    }
                    maxCashe++;
                }
                EditorGUILayout.LabelField("按钮名称");
                for (int i = 0; i < component.usePanelCount; i++)
                {
                    DrawChildPanel(component.group.GetChild(i));
                }
                if (maxCashe != 0)
                {
                    EditorUtility.SetDirty(this.component);
                }
            }
            base.OnInspectorGUI();
        }
        public void DrawChildPanel(Transform button)
        {
            var text = button.GetComponentInChildren<TextMeshProUGUI>();
            string casheText = text.text;
            text.text = EditorGUILayout.TextField(text.name, text.text);
            if (casheText != text.text)
            {
                EditorUtility.SetDirty(text);
            }
        }
    }
}

